<?php
/**
 * 首页商品列表
 * Created by PhpStorm.
 * User: Jmashimaro
 * Date: 2015/1/20
 * Time: 13:34
 */

class IndexApp extends MallbaseApp {

    /**
     * 专题详情
     * @var string
     */
    private $special_url = "http://m.heshetrends.com/index.php?c=special&a=detail&id=";
    private $common;

    public function __construct() {
        $this->common = new CommonApp();
    }


    /**
     * 首页展示四种模式 1.4版本使用
     * @author jyx
     * @date 2015/10/15
     */
    public function run() {
        $action = '首页展示内容';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR, '非法操作！');
        }
        $version = $_SERVER['HTTP_VERSION'];
        $page = $this->get_gp('page', 'G');
        $size = $this->get_gp('size', 'G');
        $size = $size ? intval($size) : 8;
        $page = $page ? intval($page) : 1;
        $offset = $page > 1 ? ($page - 1) * $size : 0;//商品翻页
        $offsets = $page > 1 ? $page - 1 : 0;//店铺或推荐翻页
        $data = $list = $special = $goods = $store = $tmp = $recommend = array();
        $model = m('goods');
//        $user_id = '101252';
        $user_id = $this->checkLogin();
        //只有第一页显示
        $tmp = ($page == 1) ? array(array(
                'subject' => '加入He She将获得：',
                'title' => '全球购、国际品牌的商品',
                'module' => -1,),) : $tmp;
        //单品模块
        $sql = "SELECT g.goods_id,g.default_image,g.goods_name,g.price,g.introduction,g.discount_price,g.is_act,g.detail_url,
            g.source,g.currency,g.act_start_time,g.act_end_time,g.store_id,gs.collects,gs.base_collects FROM ".DB_PREFIX."goods_statistics gs
            LEFT JOIN ".DB_PREFIX."goods g ON g.goods_id=gs.goods_id WHERE g.if_examine=1 AND g.if_finance=1
            AND g.if_show=1 AND g.closed=0 ORDER BY gs.collects DESC LIMIT {$offset},{$size}";
        $goodsInfo = $model->getAll($sql);
        if ($goodsInfo) {
            foreach ($goodsInfo as $key=>$val) {
                $val['module'] = 1;
                $val['collects'] = $val['collects'] + $val['base_collects'];
                $images = $stock = array();
                //查询出同一商品的其它图片
                $sql = "SELECT image_id,image_url FROM ".DB_PREFIX."goods_image WHERE goods_id={$val['goods_id']} ORDER BY image_id ASC";
                $images = $model->getAll($sql);
                if ($images) {
                    foreach ($images as $k=>$v) {
                        $v['image_url'] = $this->common->isMySelfImage($v['image_url'], GOODS_IMG);
                        $images[$k] = $v;
                    }
                }
                $val['images'] = $images;
                //获取商铺名称和logo
                $sql = "SELECT store_name,store_logo FROM ".DB_PREFIX."store WHERE store_id={$val['store_id']}";
                $store = $model->getRow($sql);
                $val['store_name'] = $store['store_name'];
                $val['store_logo'] = $store['store_logo'] ? QINIU_URL.$store['store_logo'] : '';
                //查询出商品的总库存数
                $sql = "SELECT SUM(stock) AS total_stock FROM ".DB_PREFIX."goods_spec WHERE goods_id={$val['goods_id']} ORDER BY spec_id DESC";
                $stock = $model->getRow($sql);
                $val['total_stock'] = $stock['total_stock'] ? intval($stock['total_stock']) : 0;
                $val['follow'] = $user_id ? $this->common->getRelationShip($user_id, $val['goods_id']) : 0;
                $val['default_image'] = $this->common->isMySelfImage($val['default_image'], GOODS_IMG);
                $val['discount'] = $this->common->isAct($val['is_act'], $val['act_start_time'], $val['act_end_time']);//有无折扣价
                $goodsInfo[$key] = $val;
            }
        }
        //店铺模块
        //获取商铺信息
        //查询商铺的总数量
//        $sql = "SELECT COUNT(store_id) AS num FROM ".DB_PREFIX."store WHERE state = 1 ORDER BY collects DESC";
//        $storeCount = $model->getRow($sql);
//        // 如果店达到最大数量时就不显示店铺了
//        if ($offsets <= $storeCount['num']) {
//            $sql = "SELECT store_id,store_name,store_logo FROM ".DB_PREFIX."store WHERE state = 1
//                ORDER BY store_id DESC LIMIT {$offsets},1";
//            $store = $model->getAll($sql);
//            if ($store) {
//                foreach($store as $key=>$val) {
//                    $val['module'] = 2;
//                    $val['store_logo'] = $val['store_logo'] ? QINIU_URL.$val['store_logo'] : '';
//                    $val['follow'] = $user_id ? $this->common->getRelationShip($user_id, $val['store_id'], 'store') : 0;//是否关注此商铺
//                    //获取商铺下的商品信息
//                    $sql = "SELECT g.goods_id,g.goods_name,g.introduction,g.default_image,g.price,g.detail_url,g.source,g.currency,
//                        g.is_act,g.discount_price,g.act_start_time,g.act_end_time,gs.collects,gs.base_collects FROM ".DB_PREFIX."goods g
//                        LEFT JOIN ".DB_PREFIX."goods_statistics gs ON g.goods_id=gs.goods_id WHERE store_id={$val['store_id']}
//                        AND g.if_examine=1 AND g.if_finance=1 AND g.if_show=1 AND g.closed = 0 ORDER BY gs.collects DESC LIMIT 5";
//                    $goods = $model->getAll($sql);
//                    if ($goods) {
//                        foreach ($goods as $k=>$v) {
//                            $v['collects'] = $v['collects'] + $v['base_collects'];
//                            $v['follow'] = $user_id ? $this->common->getRelationShip($user_id, $v['goods_id']) : 0;//是否关注此商品
//                            $v['discount'] = $this->common->isAct($v['is_act'], $v['act_start_time'], $v['act_end_time']);//是否优惠
//                            $v['default_image'] = $this->common->isMySelfImage($v['default_image'], GOODS_S_IMG);
//                            $goods[$k] = $v;
//                        }
//                    }
//                    $val['goods'] = $goods;
//                    $store[$key] = $val;
//                }
//            }
//            unset($goods);
//        }
        //专题模块
        //获取专题信息
        //查询推荐的总数量
//        $sql = "SELECT COUNT(id) AS num FROM ".DB_PREFIX."special ORDER BY id DESC";
//        $specialCount = $model->getRow($sql);
//        if ($offsets <= $specialCount['num']) {
//            $sql = "SELECT id,`name`,start_time,end_time,ctype,video_url,share_text,share_img
//                 FROM ".DB_PREFIX."special WHERE `status`=1 AND (start_time=0 or start_time<".time().") and (end_time=0 or end_time>".time().") ORDER BY sort,id DESC LIMIT {$offsets},1";
//            $special = $model->getAll($sql);
//            if ($special) {
//                $time = time();
//                foreach ($special as $key=>$val) {
//                    $type = $val['ctype'] ? 2 : 0;
//                    $sql = "SELECT src FROM ".DB_PREFIX."special_img WHERE type={$type} AND spec_id=".$val['id'];
//                    $images = $model->getRow($sql);
//                    $val['img_path'] = $images['src'] ? QINIU_URL.$images['src'].DISCOVERY : '';
//                    $val['module'] = 3;
//                    $val['url'] = $this->special_url.$val['id'];
//                    $val['share_img'] = $val['share_img'] ? QINIU_URL.$val['share_img'] : '';
//                    $val['is_show'] = ($time > $val['start_time'] && $time < $val['end_time']) ? 1 : 0;//是否显示此专题
//                    //获取当前专题下的商品信息
//                    $sql = "SELECT g.goods_id,g.goods_name,g.introduction,g.default_image,g.price,g.source,g.currency,g.is_act,
//                        g.discount_price,g.act_start_time,g.act_end_time,gs.collects,gs.base_collects FROM ".DB_PREFIX."goods g
//                        LEFT JOIN ".DB_PREFIX."goods_statistics gs ON g.goods_id=gs.goods_id WHERE g.goods_id IN
//                        (SELECT goods_id FROM ".DB_PREFIX."special_goods WHERE spec_id={$val['id']})
//                        AND g.if_examine = 1 AND g.if_finance = 1 AND g.if_show = 1 AND g.closed = 0
//                        ORDER BY g.last_update DESC LIMIT 5;";
//                    $goods = $model->getAll($sql);
//                    if ($goods) {
//                        foreach ($goods as $k=>$v) {
//                            $v['collects'] = $v['collects'] + $v['base_collects'];
//                            $v['discount'] = $this->common->isAct($v['is_act'], $v['act_start_time'], $v['act_end_time']);
//                            $v['follow'] = $user_id ? $this->common->getRelationShip($user_id, $v['goods_id']) : 0;//是否关注了此商品
//                            $v['default_image'] = $this->common->isMySelfImage($v['default_image'], DISCOVERY_GOODS_IMG);
//                            $goods[$k] = $v;
//                        }
//                    }
//                    $val['goods'] = $goods;
//                    $special[$key] = $val;
//                }
//            }
//            unset($goods);
//        }
        $data = array_merge($goodsInfo, $store, $special);

        //首页推荐广告模式,只有第一页显示
        if ($page == 1) {
            $specialInfo = $this->getSpecial($model, $user_id);
            if ($specialInfo) {
                $data = array_merge($specialInfo, $data);
            }
        }
        //如果未登陆，显示$tmp数组
        $data = $user_id ? $data : array_merge($tmp, $data);
        $this->ajax_return(FLAG_OK, '', array_values ( $data ));
    }


    /**
     * 首页推荐广告
     * @param $model
     * @param $user_id
     * @return array
     * @author jyx
     * @date 2015/11/30
     */
    private function getSpecial($model, $user_id) {
        $data = array();
        $time = $_REQUEST ['REQUEST_TIME'];
        $sql = "SELECT id,`name`,item_id,ctype,sort,start_time,end_time FROM ".DB_PREFIX."iostart WHERE `status`=1 ORDER BY sort DESC";
        $info = $model->getAll($sql);
        if ($info) {
            foreach($info as $key=>$val) {
                $type = $val['ctype'];

                /************************************************************************************************************/
                /************************************************************************************************************/
                /************************************************************************************************************/
                /**
                 * 解决因为时间限制为无限导致的推广主题不显示问题
                 *
                 * @author mingyang.sun
                 * @date 2016-03-15
                 */
                // 默认为不显示
                $flag = 0;
                // 开始时间为0 不限制
                // 开始时间小于当前时间,可以显示
                if ( $val ['start_time'] == 0 or $time > $val['start_time'])
                {
                    $flag = 1;
                }
                // 结束时间为0 不限制
                // 结束时间大于当前时间,可以显示
                if ( $val ['end_time'] === 0 or $time < $val['end_time'] )
                {
                    $flag = 1;
                }
                /************************************************************************************************************/
                /************************************************************************************************************/
                /************************************************************************************************************/

//                if ( $val ['end_time'] > 0 )
//                {
//                    $flag = (($time > $val['start_time']) && ($time < $val['end_time'])) ? 1 : 0;
//                }

                //如果在当前时间内
                if ($flag == 1) {
                    if ($type == 1) {//商品信息
                        $sql = "SELECT g.goods_id,g.default_image,g.goods_name,g.store_id,g.price,g.introduction,g.discount_price,
                            g.is_act,g.detail_url,g.currency,g.source,g.act_start_time,g.act_end_time,g.store_id,gs.collects,gs.base_collects
                            FROM ".DB_PREFIX."goods_statistics gs LEFT JOIN ".DB_PREFIX."goods g ON g.goods_id=gs.goods_id
                            WHERE g.goods_id={$val['item_id']} AND g.if_examine=1 AND g.if_finance=1 AND g.if_show=1
                            AND g.closed=0 LIMIT 1";
                        $goods = $model->getRow($sql);
                        if ($goods) {
                            $goods['module'] = 1;
                            $goods['collects'] = $goods['collects'] + $goods['base_collects'];
                            //获取商铺名称和logo
                            $sql = "SELECT store_name,store_logo FROM ".DB_PREFIX."store WHERE store_id={$goods['store_id']}";
                            $store = $model->getRow($sql);
                            $goods['store_name'] = $store['store_name'];
                            $goods['store_logo'] = $store['store_logo'] ? QINIU_URL.$store['store_logo'] : '';
                            //查询出商品的总库存数
                            $sql = "SELECT SUM(stock) AS total_stock FROM ".DB_PREFIX."goods_spec WHERE goods_id={$goods['goods_id']} ORDER BY spec_id DESC";
                            $stock = $model->getRow($sql);
                            $goods['total_stock'] = $stock['total_stock'] ? intval($stock['total_stock']) : 0;
                            $goods['follow'] = $user_id ? $this->common->getFollowShip($model, $user_id, $goods['goods_id']) : 0;
                            $goods['default_image'] = $this->common->isMySelfImage($goods['default_image'], GOODS_IMG);
                            $goods['discount'] = $this->common->isAct($goods['is_act'], $goods['act_start_time'], $goods['act_end_time']);//有无折扣价
                            //查询出同一商品的其它图片
                            $sql = "SELECT image_id,image_url FROM ".DB_PREFIX."goods_image WHERE goods_id={$val['item_id']} ORDER BY image_id ASC";
                            $images = $model->getAll($sql);
                            if ($images) {
                                foreach ($images as $k=>$v) {
                                    $v['image_url'] = $this->common->isMySelfImage($v['image_url'], GOODS_IMG);
                                    $images[$k] = $v;
                                }
                            }
                            $goods['images'] = $images;
                        }
                        $data[] = $goods;
                    } elseif ($type == 2) {//商铺信息
                        //获取商铺名的信息
                        $sql = "SELECT store_id,store_name,store_logo FROM ".DB_PREFIX."store WHERE store_id={$val['item_id']}";
                        $store = $model->getRow($sql);
                        if ($store) {
                            $store['module'] = 2;
                            $store['store_logo'] = $store['store_logo'] ? QINIU_URL.$store['store_logo'] : '';
                            $store['follow'] = $user_id ? $this->common->getFollowShip($model, $user_id, $store['store_id'], 'store') : 0;//是否关注此商铺
                            //获取商铺下的商品
                            $sql = "SELECT g.goods_id,g.goods_name,g.introduction,g.default_image,g.price,g.detail_url,g.source,g.currency,
                            g.is_act,g.discount_price,g.act_start_time,g.act_end_time,gs.collects,gs.base_collects FROM ".DB_PREFIX."goods g
                            LEFT JOIN ".DB_PREFIX."goods_statistics gs ON g.goods_id=gs.goods_id WHERE store_id={$val['item_id']}
                            AND g.if_examine=1 AND g.if_finance=1 AND g.if_show=1 AND g.closed = 0 ORDER BY gs.collects DESC LIMIT 5";
                            $goods = $model->getAll($sql);
                            if ($goods) {
                                foreach ($goods as $k=>$v) {
                                    $v['collects'] = $v['collects'] + $v['base_collects'];
                                    $v['default_image'] = $this->common->isMySelfImage($v['default_image'], GOODS_S_IMG);
                                    $v['follow'] = $user_id ? $this->common->getFollowShip($model, $user_id, $v['goods_id']) : 0;//是否关注此商品
                                    $v['discount'] = $this->common->isAct($v['is_act'], $v['act_start_time'], $v['act_end_time']);//是否优惠
                                    $goods[$k] = $v;
                                }
                            }
                            $store['goods'] = $goods;
                        }
                        $data[] = $store;
                    } elseif ($type == 3) {//专题信息
                        $sql = "SELECT id,`name`,content,start_time,end_time,ctype,video_url,share_text,share_img
                                FROM ".DB_PREFIX."special WHERE id={$val['item_id']} AND `status`=1  ORDER BY sort DESC LIMIT 1";
                        $special = $model->getRow($sql);
                        if ($special) {
                            $type = $special['ctype'] ? 2 : 0;
                            $sql = "SELECT src FROM ".DB_PREFIX."special_img WHERE type={$type} AND spec_id=".$special['id'];
                            $images = $model->getRow($sql);
                            $special['img_path'] = $images['src'] ? QINIU_URL.$images['src'].DISCOVERY : '';
                            $special['module'] = 3;
                            $special['url'] = $this->special_url.$special['id'];
                            $special['share_img'] = $special['share_img'] ? QINIU_URL.$special['share_img'].DISCOVERY : '';
                            $val['is_show'] = ($time > $val['start_time'] && $time < $val['end_time']) ? 1 : 0;//是否显示此专题
                            //获取当前专题下的商品信息
                            $sql = "SELECT g.goods_id,g.goods_name,g.introduction,g.default_image,g.price,g.currency,g.source,g.is_act,
                                g.discount_price,g.act_start_time,g.act_end_time,gs.collects,gs.base_collects FROM ".DB_PREFIX."goods g
                                LEFT JOIN ".DB_PREFIX."goods_statistics gs ON g.goods_id=gs.goods_id WHERE g.goods_id IN
                                (SELECT goods_id FROM ".DB_PREFIX."special_goods WHERE spec_id={$val['item_id']})
                                AND g.if_examine = 1 AND g.if_finance = 1 AND g.if_show = 1 AND g.closed = 0 GROUP BY g.goods_id
                                ORDER BY g.last_update DESC LIMIT 5;";
                            $goods = $model->getAll($sql);
                            foreach ($goods as $k => $v) {
                                $v['collects'] = $v['collects'] + $v['base_collects'];
                                $v['follow'] = $user_id ? $this->common->getFollowShip($model,$user_id, $v['goods_id']) : 0;//是否关注此商品
                                $v['default_image'] = $this->common->isMySelfImage($v['default_image'], GOODS_S_IMG);
                                $v['discount'] = $this->common->isAct($v['is_act'], $v['act_start_time'], $v['act_end_time']);//是否优惠
                                $goods[$k] = $v;
                            }
                            $special['goods'] = $goods;
                        }
                        $data[] = $special;
                    }
                }
            }
        }
//        echo '<pre>';print_r($data);die;
        return array_slice($data,0,10);
    }

    /**
     * 升级版本
     * @author jyx
     * @date 2015/12/11
     */
    public function versionUpdate() {
        $action = '升级版本';
        setLogParameter($action);
        $method = $_SERVER['REQUEST_METHOD'];
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR, '非法请求!');
        }
        $this->ajax_return(FLAG_OK, '', array('version'=>IOS_VERSION));
    }

    /**
     * 获取购物车中商品的数量,1.5版本使用
     * @return int
     * @author jyx
     * @date 2015/12/17
     */
    public function getCartGoodsCount() {
        $action = '获取购物车中商品的数量,1.5版本使用';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR, '非法的请求!');
        }
        $user_id = $this->checkLogin();
        $count = 0;
        if ($user_id) {
            $model = m('cart');
            $sql = "SELECT SUM(quantity) AS num FROM ".DB_PREFIX."cart WHERE user_id={$user_id}";
            $info = $model->getRow($sql);
            $count = $info['num'] ? intval($info['num']) : 0;
        }
        $this->ajax_return(FLAG_ERROR, '', array('count'=>$count));
    }



}

